package com.jmpt.yhn.service.Impl;

import com.jmpt.yhn.dao.JizhangReponsitory;
import com.jmpt.yhn.entity.Money;
import com.jmpt.yhn.service.JizhangService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

@Slf4j
@Service
public class JizhangServiceImpl implements JizhangService {
    @Autowired
    private JizhangReponsitory jizhangReponsitory;

    @Override
    public String deleteMoney(Integer id,String openid) {
        Money money = jizhangReponsitory.findById(id);
        if(money!=null) {
            if (openid.equals(money.getOpenid())) {
                jizhangReponsitory.delete(money);
                return "seccuss";
            }
            return "fail";
        }
        return "fail";
    }

    @Override
    public Page<Money> findByOpenid(String openid, Pageable pageable) {
        Sort sort = new Sort(Sort.Direction.DESC,"moneyTime");   //降序----根据创建时间来进行降序
        log.info("page={},size={}",pageable.getPageNumber(),pageable.getPageSize());
        PageRequest request = new PageRequest(pageable.getPageNumber(),pageable.getPageSize(),sort);  //第0页，取一条
        Page<Money> eventPage = jizhangReponsitory.findByOpenid(openid,request);
        return eventPage;
    }

    @Override
    public Money saveMoney(Money money) {
        return jizhangReponsitory.save(money);
    }

    @Override
    public List<Money> findByOpenid(String openid) {
        return jizhangReponsitory.findByOpenid(openid);
    }

    @Override
    public List<Money> findByType(String type) {
       return jizhangReponsitory.findByType(type);
    }

    @Override
    public Long countByOpenid(String openid) {
        return jizhangReponsitory.countByOpenid(openid);
    }

    @Override
    public Money updateMoney(Money money,String openid) {
        System.out.println(money);
        Money money2 = jizhangReponsitory.findById(money.getId());
        System.out.println("money2:"+money2);
        if(money2!=null&&openid.equals(money2.getOpenid())){
            money.setOpenid(money2.getOpenid());
            money.setCreateTime(money2.getCreateTime());
            Money newMoney =jizhangReponsitory.save(money);
            return newMoney;
        }else{
            System.out.println("更新失败");
            return null;

        }
    }
}
